package com.yx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yx.entity.Address;
import com.yx.entity.User;
import com.yx.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yx
 * @since 2022-02-07
 */
@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private IAddressService as;
    @GetMapping("/selectAll")
    public List<Address> selectAll(){
        return as.list();
    }
    @GetMapping("/selectByUid")
    public List<Address> selectByUid(HttpSession session){
        User user = (User)session.getAttribute("user");
        QueryWrapper qw=new QueryWrapper();
        qw.eq("uid",user.getId());
        return as.list(qw);
    }
    @PutMapping("/updateSelected")
    public void updateSelected(@RequestBody Address address,HttpSession session){
        UpdateWrapper<Address> wrapper=new UpdateWrapper<>();
        wrapper.set("selected_state",0);
        User user = (User)session.getAttribute("user");
        wrapper.eq("uid",user.getId());
        wrapper.eq("selected_state",1);
        as.update(wrapper);
        address.setSelectedState(1);
        as.updateById(address);
    }
    @PostMapping("/add")
    public void add(@RequestBody Address address,HttpSession session){
        User user = (User)session.getAttribute("user");
        UpdateWrapper<Address> wrapper=new UpdateWrapper<>();
        wrapper.set("selected_state",0);
        wrapper.eq("uid",user.getId());
        wrapper.eq("selected_state",1);
        as.update(wrapper);

        address.setUid(user.getId());
        address.setSelectedState(1);
        address.setDeleteState(0);
        as.save(address);
    }
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable("id") int id){
        as.removeById(id);
    }
}

